package com.zhuangjie.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuangjie.security.provider.UserProvider;
import com.zhuangjie.shop.entity.Menu;
import com.zhuangjie.shop.enums.ShopRole;
import com.zhuangjie.shop.mapper.MenuMapper;
import com.zhuangjie.shop.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2023-10-06
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<Menu> queryList() {
        // 获取当前用户拥有的角色信息
        List<String> roles = UserProvider.currentUserRoles();
        // 构造查询menu条件
        LambdaQueryWrapper<Menu> queryMenuListWrapper = Wrappers.lambdaQuery(Menu.class)
                // 值超小，越靠前
                .orderByAsc(Menu::getSort);
        if (! roles.contains(ShopRole.admin)) {
            // 如果不是admin，不能获取需要admin角色的路由（否则获取所有路由）
            queryMenuListWrapper.ne(Menu::getPerms,ShopRole.admin);
        }
        // 查询返回
        List<Menu> menus = this.baseMapper.selectList(queryMenuListWrapper);
        Map<Long, Menu> menuIdMap = menus.stream().filter(menu -> menu.getParentId() == null).collect(Collectors.toMap(Menu::getId, menu -> menu));
        menus.stream().filter(menu -> menu.getParentId() != null).collect(Collectors.toList()).forEach(menu-> {
            // menu 是有上级菜单的
            // 将自己添加到对应的树上
            Menu parentMenu = menuIdMap.get(menu.getParentId());
            if (parentMenu == null) return;
            List<Menu> childrenMenus = parentMenu.getChildrenMenus();
            if (childrenMenus == null) parentMenu.setChildrenMenus( childrenMenus = new ArrayList<>());
            childrenMenus.add(menu);
            // 从原始menus中删除
            menus.remove(menu);
        });
        return menus;
    }
}
